<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="900px"
      height="600px"
      style="max-height: 800px"
      draggable
      @close="closeDialog"
      append-to-body
    >
      <el-form ref="formRef" :model="formData" :inline="true" :rules="rules">
        <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
        <div class="search-container">
          <el-row>
            <el-col :span="12">
              <el-form-item label="班组编号" prop="crewCode">
                <el-input
                  v-model="formData.crewCode"
                  placeholder="请输入班组编号"
                  clearable
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="班组名称" prop="crewName">
                <el-input
                  v-model="formData.crewName"
                  placeholder="请输入班组名称"
                  clearable
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <h4 class="mb-[20px] mt-[20px]">班组成员</h4>
        <el-card shadow="never" class="table-container">
          <template #header>
            <el-button type="success" plain @click="handleAdd">
              <i-ep-plus />
              新增</el-button
            >
          </template>
          <div class="formTable">
            <el-table
              :data="formData.crewEquipments"
              :key="Math.random"
              border
              style="max-height: 200px; overflow: auto"
            >
              <el-table-column
                label="设备名称"
                props="equipmentName"
                min-width="150"
                align="center"
                style="padding-top: 15px"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'crewEquipments.' + $index + '.equipmentsList'"
                    :rules="rules.equipment"
                  >
                    <select-device-input
                      :width="250"
                      :isMultiple="false"
                      :showSelectDevice="row.equipmentsList"
                      @get-device="
                        (id, object) => getDevice(id, object, $index)
                      "
                      :disabled="row.equipmentId != ''"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="设备编码"
                props="equipmentCode"
                align="center"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <span>{{ row.equipmentCode }}</span>
                </template>
              </el-table-column>

              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.crewEquipments.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                    ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入

defineOptions({
  name: "EAMCREWDEVICEEDIT",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

// 回显/设置设备信息

// 获取选中的数据进行回显并赋值
const noRepeat = ref(true);
function getDevice(Ids: string[], Objects: any, index: number) {
  for (let i = 0; i < formData.crewEquipments.length; i++) {
    if (formData.crewEquipments[i].equipmentId === Objects[0].id) {
      noRepeat.value = false;
      ElMessage.error("设备已存在，请重新选择");
      break;
    }
  }
  console.log(noRepeat.value);

  if (noRepeat.value == true) {
    console.log(noRepeat.value);

    formData.crewEquipments[index].equipmentsList = Objects.map((item) => {
      return {
        id: item.id,
        equipName: item.equipName,
        equipCode: item.equipCode,
      };
    });
    formData.crewEquipments[index].equipmentId = Objects[0].id;
    formData.crewEquipments[index].equipmentCode = Objects[0].equipCode;
    formData.crewEquipments[index].equipmentName = Objects[0].equipName;
  } else {
    formData.crewEquipments[index].equipmentsList = [{}];
    noRepeat.value = true;
  }
}

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData: any = reactive({
  id: "",
  crewCode: "",
  crewName: "",
  crewType: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  userDay: "",
  crewEquipments: [
    {
      id: "",
      crewId: "",
      crewCode: "",
      workCenterId: "",
      workCenterCode: "",
      equipmentId: "",
      equipmentCode: "",
      equipmentName: "",
      organizationCode: "",
      organizationId: "",
      plantCode: "",
      plantId: "",
      remarks: "",
      version: 0,
      deleted: "",
      enabled: 1,
      ids: [],
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      equipmentsList: [],
    },
  ],
  crewMembers: [],
});

/** 删除行 */
const handleDelete = (index: any) => {
  formData.crewEquipments.splice(index, 1);
};

const crewEquipments: any = {
  id: "",
  crewId: "",
  crewCode: "",
  workCenterId: "",
  workCenterCode: "",
  equipmentId: "",
  equipmentCode: "",
  equipmentName: "",
  organizationCode: "",
  organizationId: "",
  plantCode: "",
  plantId: "",
  remarks: "",
  version: 0,
  deleted: "",
  enabled: 1,
  ids: [],
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  equipmentsList: [],
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(crewEquipments));
  formData.crewEquipments.push(sondata);
};

/** rules规则 */
const rules = reactive({
  equipment: [
    {
      required: true,
      message: "请选择设备",
      trigger: "blur",
    },
  ],
});

/** 编辑时赋值 */
watch(
  () => props.data,
  async (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);

      await request({
        url: "eam/eamTeam/getCrewEquipments",
        method: "post",
        data: {
          id: newVal.id,
        },
      }).then((res) => {
        // 有id时 发请求获取设备数据并复制
        formData.crewEquipments = res.data;
        // 遍历数据 给每个数据添加equipmentsList属性 用于组件回显
        formData.crewEquipments.forEach((item: any) => {
          item.equipmentsList = [
            {
              id: item.equipmentId,
              equipCode: item.equipmentCode,
              equipName: item.equipmentName,
            },
          ];
        });
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}
const crewEquipments1: any = {
  id: "",
  crewId: "",
  crewCode: "",
  workCenterId: "",
  workCenterCode: "",
  equipmentId: "",
  equipmentCode: "",
  equipmentName: "",
  organizationCode: "",
  organizationId: "",
  plantCode: "",
  plantId: "",
  remarks: "",
  version: 0,
  deleted: "",
  enabled: 1,
  ids: [],
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  equipmentsList: [],
};
/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formData.id = "";
  formData.crewCode = "";
  formData.crewName = "";
  formData.crewType = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.crewEquipments = [crewEquipments1];
}

const loading = ref(false);

/** 班制保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/eam/eamTeam/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
</script>
